import { Module } from 'vuex'
import {
  accountLoginRequest,
  requestUserInfoById,
  requestUserMenusByRoleId
} from '../../service/login/login'
import router from '../../router/index'

import type { ILoginState } from './type'
import type { IRootState } from '../type'
import type { IAccount } from '../../service/login/type'
import localCache from '../../utils/cache'
import { mapMenuToRoutes, mapMenusToPermission } from '../../utils/map-menu'

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: [],
      permissions: []
    }
  },
  getters: {},
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    changeUserMenus(state, userMenus: any) {
      state.userMenus = userMenus
      const routes = mapMenuToRoutes(userMenus)
      routes.forEach((route) => {
        router.addRoute('main', route)
      })
      const permissions = mapMenusToPermission(userMenus)
      state.permissions = permissions
    }
  },
  actions: {
    async accountLoginAcction({ commit, dispatch }, playload: IAccount) {
      const loginRes = await accountLoginRequest(playload)
      console.log(loginRes, 'loginRes')
      const { id, token } = loginRes.data.data

      commit('changeToken', token)
      localCache.setCache('token', token)
      dispatch('getInitialDataAction', null, { root: true })
      const userInfoRes = await requestUserInfoById(id)
      const userInfo = userInfoRes.data

      commit('changeUserInfo', userInfo)
      localCache.setCache('userInfo', userInfo)
      const userMenusRes = await requestUserMenusByRoleId(userInfo.data.role.id)
      const userMenus = userMenusRes.data.data

      localCache.setCache('userMenus', userMenus)
      commit('changeUserMenus', userMenus)
      router.push('/main')
    },
    loadLocalLogin({ commit, dispatch }) {
      const token = localCache.getCache('token')
      if (token) {
        commit('changeToken', token)
        dispatch('getInitialDataAction', null, { root: true })
      }
      const userInfo = localCache.getCache('userInfo')
      if (userInfo) {
        commit('changeUserInfo', userInfo)
      }
      const userMenus = localCache.getCache('userMenus')
      if (userMenus) {
        commit('changeUserMenus', userMenus)
      }
    },

    phoneLoginAcction({ commit }, playload: any) {
      console.log('执行了phoneLoginacction', playload)
    }
  }
}

export default loginModule
